﻿using System;
using MoroMoro.Samples.ToDoList.Base.Application;
using MoroMoro.Samples.ToDoList.Base.Domain.Specifications;
using MoroMoro.Samples.ToDoList.Base.Persistence;
using MoroMoro.Samples.ToDoList.Domain.ToDos;
using MoroMoro.Samples.ToDoList.Domain.Categories;

namespace MoroMoro.Samples.ToDoList.Application.ToDos
{
    /// <summary>
    /// <see cref="ToDo"/> の一覧を読み込むスクリプトです。
    /// </summary>
    [Serializable]
    internal sealed class ToDoListLoadScript : WorkScript<ToDoListLoadOutputs, ToDoListLoadErrors>
    {
        /// <summary>
        /// <see cref="ToDoListLoadScript"/> クラスの新しいインスタンスを初期化します。
        /// </summary>
        /// <param name="workspace">作業スペース。</param>
        /// <exception cref="System.ArgumentNullException">workspace が null です。</exception>
        public ToDoListLoadScript(IWorkspace workspace)
            : base(workspace)
        {
            StateFilter = null;
        }


        /// <summary>
        /// <see cref="ToDo.State">状態</see>のフィルタを取得または設定します。
        /// </summary>
        public ToDoState? StateFilter
        {
            get;
            set;
        }

        /// <summary>
        /// <see cref="ToDo.Category">カテゴリ</see>のフィルタは取得または設定します。
        /// </summary>
        public Category CategoryFilter
        {
            get;
            set;
        }


        /// <inheritdoc/>
        protected override ExecutionResult ExecuteCore()
        {
            var specification = default(Specification<ToDo>);
            if (StateFilter.HasValue)
            {
                specification &= new ToDoStateSpecification(StateFilter.Value);
            }
            specification &= new ToDoCategorySpecification(CategoryFilter);
            var order = new ToDoStateViewpoint().Asc().Then(new ToDoRegisteredDateTimeViewpoint().Asc());
            var list = Workspace.GetRepository<ToDo>().FindList(specification, order);

            return new ToDoListLoadOutputs
            {
                List = list
            };
        }
    }
}
